Skip to content

feat(context): prototype context-scoped attributes - #8947

Merged
jack-berg merged 6 commits into
open-telemetry:mainfrom
rooks-ns:feat/context-scoped-attributes
Nov 12, 2026
Merged

jack-berg merged 6 commits into
open-telemetry:mainfrom
rooks-ns:feat/context-scoped-attributes

Conversation

@rooks-ns

@rooks-ns rooks-ns commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Overview

Prototypes Context-scoped attributes (OTEP #4931, #8532), enabling Traces, Logs, and synchronous Metrics to automatically inherit attributes from the active Context.

See https://github.com/open-telemetry/opentelemetry-java/tree/main/api/incubator#context-scoped-attributes for a usage demonstration.


Specification Contracts & Architectural Invariants

  • API (api:incubator):
    • ContextAttributes.set(Context, Attributes): Sets or replaces context-scoped attributes on a context.
    • ContextAttributes.get(Context): Reads context-scoped attributes (returns Attributes.empty() if absent).
    • Standard compile-time non-null parameter contracts backed by runtime ApiUsageLogger fail-soft guards.
  • Trace Parentage & setNoParent() (sdk:trace):
    • Context attributes merge before Sampler.shouldSample(), ensuring sampling, span creation, and SpanProcessor.onStart() observe the merged set.
    • setNoParent() isolates trace parentage and baggage to root while preserving ambient context attributes, using a static NO_PARENT context sentinel to eliminate builder heap overhead.
  • Bound Instrument Cardinality Isolation (sdk:metrics):
    • Bound instruments (BoundStorageHandle) record strictly to their pre-bound timeseries with zero runtime context evaluation or heap allocations.
    • Unbound instruments merge context attributes dynamically prior to Metric View filtering.
  • Precedence & Limits:
    • Call-site explicit attributes override context attributes on key collisions.
    • Standard signal limits (SpanLimits, LogLimits) and Metric View filters apply post-merge.
  • Configuration:
    • Disabled by default. Enabled per-signal via Sdk*ProviderUtil.setContextScopedAttributesFilter(builder, BiPredicate<InstrumentationScopeInfo, AttributeKey<?>>).

Signal Implementation Summary

Signal Attachment Point Behavior
API ContextAttributes Authoritative set() and reader get() backed by a private ContextKey.
Trace SdkSpanBuilder.startSpan() Merges before Sampler.shouldSample(); preserves ambient attributes on setNoParent().
Logs SdkLogRecordBuilder.emit() Merges on emit; enforces LogLimits and tracks dropped attributes.
Metrics DefaultSynchronousMetricStorage Unbound records merge before View filtering; bound handles bypass context.
Config Sdk*ProviderUtil Scope- and key-level filtering via BiPredicate<InstrumentationScopeInfo, AttributeKey<?>>.

Documentation & Verification

  • Documentation & Usage: Canonical multi-signal examples in ContextAttributesUsageTest; documented in api/incubator/README.md.
  • Test Suites:
    • sdk:trace: ContextScopedAttributesSpanTest (sampler inspection, trace/baggage detachment, attribute inheritance).
    • sdk:metrics: ContextScopedAttributesMetricTest (unbound dynamic inheritance, bound isolation across aggregation temporalities).
    • sdk:logs: ContextScopedAttributesLogTest (attribute inheritance, collision precedence, LogLimits accounting).
  • Static Analysis: Verified clean across spotlessCheck, checkstyle, animalsniffer, and jApiCmp.

@opentelemetry-pr-dashboard

opentelemetry-pr-dashboard Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

Pull request dashboard status

Merged · refreshed 2026-11-12 21:17 UTC

Status above doesn't look right?
  • Anything look wrong? Report it with what you expected; it helps us improve the dashboard.

@codecov

codecov Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 89.79592% with 15 lines in your changes missing coverage. Please review.
✅ Project coverage is 90.41%. Comparing base (fecfb6d) to head (9a16c44).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
...io/opentelemetry/sdk/logs/SdkLogRecordBuilder.java 86.36% 1 Missing and 2 partials ⚠️
...nternal/state/DefaultSynchronousMetricStorage.java 90.32% 1 Missing and 2 partials ⚠️
...metry/sdk/logs/internal/SdkLoggerProviderUtil.java 75.00% 2 Missing ⚠️
...try/sdk/metrics/internal/SdkMeterProviderUtil.java 75.00% 2 Missing ⚠️
...etry/sdk/trace/internal/SdkTracerProviderUtil.java 75.00% 2 Missing ⚠️
...emetry/api/incubator/common/ContextAttributes.java 94.44% 0 Missing and 1 partial ⚠️
.../opentelemetry/sdk/metrics/AbstractInstrument.java 50.00% 0 Missing and 1 partial ⚠️
...ava/io/opentelemetry/sdk/trace/SdkSpanBuilder.java 94.44% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##               main    #8947      +/-   ##
============================================
+ Coverage     90.37%   90.41%   +0.03%     
- Complexity    11018    11069      +51     
============================================
  Files          1021     1023       +2     
  Lines         30124    30254     +130     
  Branches       3933     3952      +19     
============================================
+ Hits          27225    27353     +128     
+ Misses         1941     1933       -8     
- Partials        958      968      +10     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@rooks-ns
rooks-ns force-pushed the feat/context-scoped-attributes branch from 403a57c to 7d8f465 Compare October 13, 2026 22:24
@rooks-ns
rooks-ns marked this pull request as ready for review October 14, 2026 18:25
@rooks-ns
rooks-ns requested a review from a team as a code owner October 14, 2026 18:25
@rooks-ns
rooks-ns force-pushed the feat/context-scoped-attributes branch 3 times, most recently from 3b2ce44 to e7872d7 Compare October 14, 2026 21:45
@rooks-ns
rooks-ns marked this pull request as draft October 18, 2026 12:22
@rooks-ns
rooks-ns force-pushed the feat/context-scoped-attributes branch from e7872d7 to 657d862 Compare October 19, 2026 23:48
@rooks-ns
rooks-ns marked this pull request as ready for review October 20, 2026 14:20
Implements prototype for Context-scoped attributes per OTEP open-telemetry#4931 and Issue open-telemetry#8532:
- Add ContextAttributes API in :api:incubator for setting/getting/extracting attributes on Context
- Support opt-in context-scoped attributes configuration across SdkTracerProvider, SdkLoggerProvider, and SdkMeterProvider
- Inherit context attributes in SdkSpanBuilder, SdkLogRecordBuilder, and synchronous metric storage (Delta & Cumulative)
- Expose configuration via declarative-config (tracer_provider, logger_provider, meter_provider)
- Add comprehensive unit, incubating, and multi-signal integration tests
@rooks-ns
rooks-ns force-pushed the feat/context-scoped-attributes branch from 657d862 to ef1468f Compare October 22, 2026 16:49
@rooks-ns

Copy link
Copy Markdown
Contributor Author

@jack-berg Please take a look . Thank you.

if (context == null) {
return Attributes.empty();
}
Attributes attributes = context.get(CONTEXT_ATTRIBUTES_KEY);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see usefulness in this feature but I find it hard to understand how to decide with instrumentations should include the attributes.

How to assert or qualify the carnality of the attribute?
Which instrumentations should skip an attribute?
Should we have a handler to decide which instrumentations opt to an attribute?
Are there attributes that make no sense across an entire context lifespan?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instrumentations are advised against including attributes (see javadoc at top).

Think about the core use cases: tenant id / user id. An application would add these to context early in request lifecycle via interceptor or filter. They would also configure the SDK to include the attributes as needed based on signal, scope, and and attribute key.

The OTEP left a lot of questions unanswered with the intent of discovering more via prototyping. If you have general feedback (i.e. not related to the java implementation), please add it to open-telemetry/opentelemetry-specification#5170 so all languages can benefit.

@jack-berg jack-berg left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pretty good stuff - close to what I expected. Left a few comments but nothing should be too tricky.

@opentelemetry-pr-dashboard

This comment has been minimized.

…oped attributes prototype (open-telemetry#8532)

- Trace: Isolate parent context and ambient Baggage when setNoParent() is configured by passing Context.root() to samplers/processors while resolving context attributes from current context.
- Collisions: Add amortized O(1) AttributesMap.contains(AttributeKey<?>) to enforce name-based attribute identity and ensure explicit attributes take precedence over context attributes regardless of type.
- Logs: Eliminate AttributesMap.copyOf defensive allocation by mutating builder attributes in-place during emit().
- Filtering: Upgrade trace, log, and metric providers from a boolean flag to BiPredicate<InstrumentationScopeInfo, AttributeKey<?>> contextScopedAttributesFilter; curry predicate in SdkMeter for synchronous metric storage; preserve context-oblivious bound instruments.
- API: Add ContextAttributes.set() for replacement and clearing, retain add() for additive merging, enforce strict requireNonNull validation, and record maintainer deprecation TODO.
- Config: Revert declarative-config prototype additions to match upstream main.
@rooks-ns
rooks-ns force-pushed the feat/context-scoped-attributes branch from 12e5e76 to a9bcfb9 Compare November 6, 2026 18:18
if (context == null) {
return Attributes.empty();
}
Attributes attributes = context.get(CONTEXT_ATTRIBUTES_KEY);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instrumentations are advised against including attributes (see javadoc at top).

Think about the core use cases: tenant id / user id. An application would add these to context early in request lifecycle via interceptor or filter. They would also configure the SDK to include the attributes as needed based on signal, scope, and and attribute key.

The OTEP left a lot of questions unanswered with the intent of discovering more via prototyping. If you have general feedback (i.e. not related to the java implementation), please add it to open-telemetry/opentelemetry-specification#5170 so all languages can benefit.

…tributes prototype (open-telemetry#8532)

- API: Gate deprecation TODO on spec PR 4931, streamline Javadoc to focus on opt-in SDK stamping and metric cardinality risks, and gracefully degrade on null params via ApiUsageLogger.
- AttributesMap: Rename contains(AttributeKey) to containsKey(String) to reflect name-only lookup semantics.
- Providers: Remove deprecated setContextScopedAttributesEnabled(boolean) across Trace, Log, and Metric providers and utils in favor of the canonical filter predicate.
- Logs: Extract populateContextAttributes helper with fast-exit on empty context attributes, and remove redundant compiler warning suppressions.
- Metrics: Guard incubating reflection utilities with INCUBATOR_AVAILABLE across all signals, instantiate AttributesBuilder lazily only on first matching attribute, return attributes unchanged on miss, and clarify bound instruments Javadoc with review TODO.
- Tests: De-duplicate log test fixtures via @beforeeach, update all integration and unit test setups to use filter predicates, and verify graceful null degradation.
@rooks-ns
rooks-ns force-pushed the feat/context-scoped-attributes branch from 2608242 to c845277 Compare November 10, 2026 17:01
@rooks-ns
rooks-ns force-pushed the feat/context-scoped-attributes branch from 2c79d44 to 802432d Compare November 11, 2026 15:31
@rooks-ns
rooks-ns requested a review from jack-berg November 11, 2026 16:48
…tributes prototype (open-telemetry#8532)

- api: remove add(Context, Attributes) and strip @nullable parameter annotations
- api: update Javadoc on metric cardinality and bound instruments
- api: relocate integration test to ContextAttributesUsageTest and document in README
- trace: use NO_PARENT sentinel Context in SdkSpanBuilder to eliminate boolean field
- metrics: pre-curry contextScopedAttributesFilter in SdkMeter constructor
- metrics: relocate INCUBATOR_AVAILABLE to top of DefaultSynchronousMetricStorage
- logs: remove redundant this. qualifier on attributes in SdkLogRecordBuilder
- tests: modernize and streamline assertions across signals using satisfiesExactly and Mockito
@rooks-ns
rooks-ns requested a review from jack-berg November 12, 2026 18:25

@jack-berg jack-berg left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great work. Thanks!

@jack-berg
jack-berg merged commit f646d4b into open-telemetry:main Nov 12, 2026
32 of 34 checks passed
@otelbot

otelbot Bot commented Nov 12, 2026

Copy link
Copy Markdown
Contributor

Thank you for your contribution @rooks-ns! 🎉 We would like to hear from you about your experience contributing to OpenTelemetry by taking a few minutes to fill out this survey.

@jack-berg jack-berg changed the title feat(context): prototype context-scoped attributes (#8532) feat(context): prototype context-scoped attributes Nov 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants